<template>
  <n-space vertical>
    <n-form
      ref="formRef"
      :model="formValue"
      inline
      label-width="80"
      label-placement="left"
      :rules="rules"
    >
      <n-form-item label="文章名" class="input" path="title">
        <n-input v-model:value="formValue.title" />
      </n-form-item>
      <n-form-item label="分类" class="category" path="category">
        <n-select v-model:value="formValue.category" :options="categoryList" />
      </n-form-item>
      <n-form-item label="标签" class="tags" path="tags">
        <n-select v-model:value="formValue.tags" multiple :options="tagList" />
      </n-form-item>
      <n-form-item class="button">
        <n-button @click="createFunc"> 保存 </n-button>
      </n-form-item>
    </n-form>

    <Markdown
      class="markdown"
      v-model:text="formValue.content"
      v-model:htmlText="formValue.contentHtml"
    />
  </n-space>
</template>

<script setup lang="ts">
import {
  NSpace,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  NUpload,
  NUploadDragger,
  NIcon,
  NText,
  NP,
  type SelectGroupOption,
  type SelectOption,
  type FormInst,
  type UploadCustomRequestOptions,
} from "naive-ui";
import { ArchiveOutline as ArchiveIcon } from "@vicons/ionicons5";
import { findAll as apiFindAllTags } from "../../api/tag";
import { findAll as apiFindAllCategories } from "~/api/category";
import {
  type createPost,
  create as apiCreatePost,
  findByIdAdmin as apiPostFindOneById,
  updateOne as apiPostUpdateOne,
} from "~/api/post";
useHead({
  title: "文章编辑", //网站标题
});
definePageMeta({
  title: "文章管理-文章编辑",
});
const formValue = ref<createPost>({
  title: "",
  tags: [],
  category: null,
  content: "",
  contentHtml: "",
});
const rules = {
  title: {
    pattern: /^.{3,50}$/,
    message: "文章名必填，长度大于3位小于50位",
    required: true,
    trigger: "blur",
  },
  tags: {
    required: true,
    message: "标签必选",
  },
  category: {
    required: true,
    message: "分类必选",
  },
};
const formRef = ref<FormInst | null>(null);
const createFunc = (e?: MouseEvent) => {
  e?.preventDefault();
  formRef.value?.validate(async (errors) => {
    if (errors) {
      naiveui.message.error(errors[0][0].message ?? "表单验证错误");
      return;
    }
    if (!formValue.value.content) {
      naiveui.message.error("文章内容不能为空");
      return;
    }
    const { id } = route.query;
    if (id !== null && id !== undefined) {
      await apiPostUpdateOne(id as string, formValue.value);
    } else {
      const postId = (await apiCreatePost(formValue.value)).data;
      await navigateTo({
        path: "/post/writeContent",
        query: { id: postId },
      });
    }
  });
};

const tagList = ref<Array<SelectOption | SelectGroupOption>>([]);
const categoryList = ref<Array<SelectOption | SelectGroupOption>>([]);
const getcategories = async () => {
  const res = await apiFindAllCategories();
  res.data.forEach((category) => {
    categoryList.value.push({
      label: category.name,
      value: category.id,
    });
  });
};
const getTags = async () => {
  const res = await apiFindAllTags();
  res.data.forEach((tag) => {
    tagList.value.push({
      label: tag.name,
      value: tag.id,
    });
  });
};

const route = useRoute();
const findPost = async () => {
  const { id } = route.query;

  if (id !== null && id !== undefined) {
    const res = await apiPostFindOneById(id as string);
    if (res.code === 0) {
      const { title, tags, category, content, contentHtml } = res.data;
      formValue.value.title = title;
      formValue.value.tags = tags.map((t) => t.id);
      formValue.value.category = category.id;
      formValue.value.content = content ?? "";
      formValue.value.contentHtml = contentHtml ?? "";
    }
  }
};
onMounted(async () => {
  getcategories();
  getTags();
  findPost();
  document.addEventListener("keydown", function (event) {
    if (
      (event.ctrlKey && event.key === "s") ||
      (event.metaKey && event.key === "s")
    ) {
      event.preventDefault();
      createFunc();
    }
  });
});
</script>
<style lang="scss" scoped>
.button {
  height: 100%;
  display: flex;
  align-items: center;
}

.input {
  flex: 3;
}

.category {
  flex: 1;
}

.tags {
  flex: 2;
}

.button {
  padding-right: 20px;
}

.markdown {
  height: 80vh;
}

.n-form {
  :deep(.n-tag) {
    --n-color: var(--n-color);
  }
}
</style>
